// 检查图片是否存在
function check_img_exists(imgurl) {  
    var ImgObj = new Image(); //判断图片是否存在  
    ImgObj.src = imgurl;
    //没有图片，则返回-1  
    if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {  
        return true;  
    } else {  
        return false;
    }  
} 

// 表单提交方法
function form_submit(form, postUrl, callback){
	form.submit(function(e){
        e.preventDefault();
        var array= $(this).serializeArray();
        //遍历对象
        var data = {};
        $.each(array, function(e){
        	if(typeof data[array[e].name] != 'undefined') {
        		data[array[e].name] += "," + array[e].value;
        	} else {
        		data[array[e].name] = array[e].value;	
        	}
        });

        // 加载提示
        layer.load(2, {
            opacity: 0.3
        });
        $.post(
            postUrl, data, function(res) {
                layer.closeAll('loading');
                if(typeof callback != 'undefined' && callback) callback(res);
            }
        , "json")
    })
}

// 会自动关闭的弹窗提示
function tips_alert(msg, success, callback){
    //提示层
    layer.msg(msg, {
        icon: success ? 1 : 2,
        shade: 0.5,
        shadeClose: true,
        offset: '300px',
        end: function() {
            typeof callback == 'undefined' || callback();
        }
    });
}

// 封装ajax的get，post方法
function ajax_get(url, params, success, fail){
    // 如果有hideLoading参数，就不显示遮罩层
    if(typeof params.hideLoading == 'undefined') layer.load(1);

    $.get(
        url, params, function(res) {
            if(typeof params.noHideLoading == 'undefined') layer.closeAll('loading');
            if(res.success) {
                if(res.msg) {
                    tips_alert(res.msg, true, function(){
                        typeof success == 'undefined' || success(res);
                    });
                } else {
                    typeof success == 'undefined' || success(res);
                }
            } else {
                if(res.msg) {
                    tips_alert(res.msg, false, function() {
                        typeof fail == 'undefined' || fail(res);
                    });
                } else {
                    typeof fail == 'undefined' || fail(res);
                }
            }
        }
    , "json")
}
function ajax_post(url, params, success, fail){
    if(typeof params.hideLoading == 'undefined') {
        // layer.load(1);
        layer.load(1, {
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '39px',
                    'width': '60px',
                    'color': '#FFF'
                });
            }
        });
    }

    $.post(
        url, params, function(res) {
            if(typeof params.noHideLoading == 'undefined') layer.closeAll('loading');
            if(res.success) {
                if(res.msg) {
                    tips_alert(res.msg, true, function(){
                        typeof success == 'undefined' || success(res);
                    });
                } else {
                    typeof success == 'undefined' || success(res);
                }
            } else {
                if(res.msg) {
                    tips_alert(res.msg, false, function() {
                        typeof fail == 'undefined' || fail(res);
                    });
                } else {
                    typeof fail == 'undefined' || fail(res);
                }
            }
        }
    , "json")
}
// 手机端不显示遮罩层
function ajax_get_by_mob(url, params, success, fail){
    $.get(
        url, params, function(res) {
            if(res.success) {
                if(res.msg) {
                    // tips_alert(res.msg, true, function(){
                    //     typeof success == 'undefined' || success(res);
                    // });
                    $.toast(res.msg, "success", function() {
                        typeof success == 'undefined' || success(res);
                    });
                } else {
                    typeof success == 'undefined' || success(res);
                }
            } else {
                if(res.msg) {
                    // tips_alert(res.msg, false, function() {
                    //     if(res.fail) fail(res);
                    // });
                    $.toast(res.msg, "cancel", function() {
                        if(res.fail) fail(res);
                    });
                } else {
                    if(res.fail) fail(res);
                }
            }
        }
    , "json")
}
// 手机端请求成功提示样式
function ajax_post_by_mob(url, params, success, fail){
    if(typeof params.hideLoading == 'undefined') {
        $.showLoading();
    }
    $.post(
        url, params, function(res) {
            if(typeof params.hideLoading == 'undefined') $.hideLoading();
            if(res.success) {
                if(res.msg) {
                    if(typeof params.hideToast == 'undefined') {
                        $.toast(res.msg, "success", function() {
                            success(res);
                        });
                    } else {
                        success(res);
                    }
                } else {
                    typeof success == 'undefined' || success(res);
                }
            } else {
                if(res.msg) {
                    if(typeof params.hideToast == 'undefined') {
                        $.toast(res.msg, "cancel", function() {
                            if(res.fail) fail(res);
                        });
                    } else {
                        if(res.fail) fail(res);
                    }
                } else {
                    // typeof fail == 'undefined' || fail(res);
                    if(res.fail)  fail(res);
                }
            }
        }
    , "json")
}

// 封装DataTable
$.fn.dt = function(options) {
    var options = $.extend({
        "ajaxUrl": "",      // ajax请求的地址
        "ajaxData": {},     // ajax请求的参数
        "columns": {},
        "callback": null    // 回调，可以获取到添加的元素
    }, options);
    var me = $(this);

    // 初始化表格
    var dt = me.DataTable({
        // 自定义表格布局
        "sDom":'rt<"bottom row"<"col-xs-3"i><"col-xs-3"l>p<"clear">>',
        // 每页数据显示条数
        "pageLength": pageSize,
        "pagingType": "full_numbers",
        // 排序
        "ordering": false,
        // 是否可以修改列表长度
        "lengthChange": true,
        "iDisplayLength": pageSize,
        "aLengthMenu": [20 ,30 ,50, 100],
        // 是否显示加载中
        "processing": false,
        // 是否支持本地搜索
        "searching": false,
        // 是否由服务器加载数据
        "serverSide": true,
        "ajax": {
            "url": options.ajaxUrl,
            "data": options.ajaxData
        },
        // 语言
        "language": {
            'lengthMenu': '每页显示 _MENU_ 条数据',
            "sZeroRecords": "没有查询结果",
            "sInfo": "显示第 _START_ 至 _END_ 条结果，共 _TOTAL_ 条结果",
            "sInfoEmpty": "表中数据为空",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            },
        },
        "columns": options.columns
    });
    // 添加一个外部参数
    dt.setAjaxData = function(params){
        dt.settings()[0].ajax.data = params;
        dt.ajax.reload();
    }

     // 是否有回调方法
     if(options.callback) {
        options.callback();
    }

    return dt;
}

// 封装DataTable，供新ui项目
$.fn.dt_hzy = function(options) {
    var options = $.extend({
        "ajaxUrl": "",      // ajax请求的地址
        "ajaxData": {},     // ajax请求的参数
        "columns": {},
        "callback": null    // 回调，可以获取到添加的元素
    }, options);
    var me = $(this);

    // 初始化表格
    var dt = me.DataTable({
        // 每页数据显示条数
        "pageLength": 10,
        "pagingType": "full_numbers",
        // 排序
        "ordering": false,
        // 是否可以修改列表长度
        "lengthChange": false,
        // 是否显示加载中
        "processing": true,
        // 是否支持本地搜索
        "searching": false,
        // 是否由服务器加载数据
        "serverSide": true,
        "ajax": {
            "url": options.ajaxUrl,
            "data": options.ajaxData
        },
        // 语言
        "language": {
            "sZeroRecords": "没有查询结果",
            "sInfo": "共 _TOTAL_ 条",
            "sInfoEmpty": "表中数据为空",
            "oPaginate": {
                "sFirst": false,
                "sPrevious": '<i class="fa fa-angle-left"></i>',
                "sNext": '<i class="fa fa-angle-right"></i>',
                "sLast": false
            },
        },
        "columns": options.columns,
        // "dom": function(){
        //     $(".dataTables_info").css('color', 'red');
        // }
    });
    // 添加一个外部参数
    dt.setAjaxData = function(params){
        dt.settings()[0].ajax.data = params;
        dt.ajax.reload();
    }

     // 是否有回调方法
    if(options.callback) {
        options.callback();
    }
    // 自定义‘显示条数’
    setTimeout(() => {
        var t = ($(".dataTables_info").html());
        var h = "<span class='page-count' style='color:#666666;font-size:12px;position:relative; top:-7px'>" + t + "</span>";
        if(t != '' && $("#dynamic-table_paginate").find(".page-count").length === 0) {
            $(".pagination").before(h);
        }
    }, 100);
    setTimeout(() => {
        var t = ($(".dataTables_info").html());
        var h = "<span class='page-count' style='color:#666666;font-size:12px;position:relative; top:-7px'>" + t + "</span>";
        if(t != '' && $("#dynamic-table_paginate").find(".page-count").length === 0) {
            $(".pagination").before(h);
        }
    }, 200);
    setTimeout(() => {
        var t = ($(".dataTables_info").html());
        var h = "<span class='page-count' style='color:#666666;font-size:12px;position:relative; top:-7px'>" + t + "</span>";
        if(t != '' && $("#dynamic-table_paginate").find(".page-count").length === 0) {
            $(".pagination").before(h);
        }
    }, 300);
    setTimeout(() => {
        var t = ($(".dataTables_info").html());
        var h = "<span class='page-count' style='color:#666666;font-size:12px;position:relative; top:-7px'>" + t + "</span>";
        if(t != '' && $("#dynamic-table_paginate").find(".page-count").length === 0) {
            $(".pagination").before(h);
        }
    }, 1000);

    return dt;
}

// 上传文件控件
$.fn.uploader = function(options){
    var options = $.extend({
        "multiple": false,
        "server": "",
        "accept": "image",
        "callback": function(){}
    }, options);
    var me = $(this);

    // 文件类型限制
    var accept = "";
    var sizeLimit = "";
    switch(options.accept){	
        case 'image':
            accept = {
                title: 'Images',
                mimeTypes: 'image/*'
            };
            sizeLimit = 10*1024*1024;
            break;
        case 'video':
            accept = {
                title: 'Video',
                mimeTypes: 'video/*'
            };
            sizeLimit = 500*1024*1024;
            break;
        case 'audio':
            accept = {
                title: 'Audio',
                mimeTypes: 'audio/*'
            };
            sizeLimit = 10*1024*1024;
            break;
        case 'xls':
            accept = {
                title: 'xls',
                mimeTypes: '.xls'
            };
            sizeLimit = 500*1024*1024; // 用于导入excel,大小限制放宽为500m
            break;
        case 'all':
            accept = {
                title: 'all',
                mimeTypes: '*'
            };
            sizeLimit = 10*1024*1024;
            break;
        default:        // 默认可以选择所有
            accept = {
                title: 'all',
                mimeTypes: '*'
            };
            sizeLimit = 10*1024*1024; // 用于导入excel,大小限制放宽为500m
            break;
    }

    // 初始化上传控件
    var uploader = WebUploader.create({
        auto: true,
        pick: {
            "id": "#"+ me.attr("id"),
            "multiple": options.multiple
        },
        server: options.server,
        // server: "http://192.168.1.111/rmx/local_upload",
        // formData:{
        //     authorization: options.authorization,
        //     policy: options.policy
        // },
        accept: accept,
        // 支持重复上传
        duplicate :true,
        fileSingleSizeLimit: sizeLimit  // 限制大小500m
    });

    // 开始上传
    uploader.on("uploadStart", function() {
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            $('body').append('<div class="shadow" style="display:flex;justify-content:center;align-items:center;padding-bottom:10%;width: 100%;height: 100%;position:fixed; top:0;left:0;background-color: #000;z-index: 9999;background: rgba(0,0,0,0.6)">\
                <div class="progress progress-striped pos-rel active" style="width: 50%;height: 28px;text-align:center;border-radius: 20px;z-index:9999;">\
                    <div class="progress-bar progress-bar-success" style="line-height: 28px;width: 0%;">\
                    <span style="color:#fff;">0%</span>\
                    </div>\
                </div>\
            </div>');
        }
    })
    // 上传中
    uploader.on('uploadProgress', function( file, percentage ) {
        // 上传视频时显示进度条
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            var percentage = Math.floor(percentage * 10000) / 100;
            $(".progress span").text(percentage + "%");
            $(".progress .progress-bar").width(percentage + "%")
        } else {
            layer.load(2, {
                opacity: 0.3
            });
        }
    })
    // 上传完成
    uploader.on('uploadSuccess', function(file, response) {
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            $('.progress').remove();
            $('.shadow').remove();
        } else {
            layer.closeAll('loading');
        }
        layer.closeAll('loading');
        // 新增一个文件名字段
        response.name = encodeURIComponent(file.name);
        options.callback(response);
    });
    // 上传错误
    uploader.on("error", function (type) {
        toastr.options = {  
            positionClass: "toast-center-center",              // 设置提示款显示的位置
            showDuration: "300",                               // 显示动画的时间
            hideDuration: "1000",                              //  消失的动画时间
            timeOut: "2000"                                    //  自动关闭超时时间 
        };
        if (type == "F_EXCEED_SIZE") {
            if(sizeLimit == 10*1024*1024) {
                toastr.error('文件大小不能超过10M');
            } else if(sizeLimit == 50*1024*1024) {
                toastr.error('文件大小不能超过50M');
            } else if(sizeLimit == 500*1024*1024) {
                toastr.error('文件大小不能超过500M');
            } else {
                toastr.error('文件大小不能超过10M');
            }
        } else {
            toastr.error("上传出错！请检查后重新上传！错误代码" + type);
        }
    });
}

// 上传文件控件，手机端进度条
$.fn.uploaderForMob = function(options){
    var options = $.extend({
        "multiple": false,
        "server": "",
        "accept": "image",
        "authorization": "",
        "policy": "",
        "callback": function(){}
    }, options);
    var me = $(this);

    // 文件类型限制
    var accept = "";
    var sizeLimit = "";
    switch(options.accept){	
        case 'image':
            accept = {
                title: 'Images',
                mimeTypes: 'image/*'
            };
            sizeLimit = 10*1024*1024;
            break;
        case 'video':
            accept = {
                title: 'Video',
                mimeTypes: 'video/*'
            };
            sizeLimit = 50*1024*1024;
            break;
        case 'audio':
            accept = {
                title: 'Audio',
                mimeTypes: 'audio/*'
            };
            sizeLimit = 10*1024*1024;
            break;
        case 'xls':
            accept = {
                title: 'xls',
                mimeTypes: '.xls'
            };
            sizeLimit = 500*1024*1024; // 用于导入excel,大小限制放宽为500m
            break;
        case 'all': // 附件
            accept = {
                title: 'all',
                mimeTypes: '*'
            };
            sizeLimit = 10*1024*1024;
            break;
        default:        // 默认可以选择所有
            accept = {
                title: 'all',
                mimeTypes: '*'
            };
            sizeLimit = 10*1024*1024; // 用于导入excel,大小限制放宽为500m
            break;
    }
    // // 图片
    // if(options.accept == 'image') {
    //     accept = {
    //         title: 'Images',
    //         mimeTypes: 'image/*'
    //     };
    //     sizeLimit = 10*1024*1024;
    // }
    // // 视频
    // if(options.accept == 'video') {
    //     accept = {
    //         title: 'Video',
    //         mimeTypes: 'video/*'
    //     };
    //     sizeLimit = 50*1024*1024;
    // }
    // // 音频
    // if(options.accept == 'audio') {
    //     accept = {
    //         title: 'Audio',
    //         mimeTypes: 'audio/*'
    //     };
    //     sizeLimit = 10*1024*1024;
    // }
    // // 音频
    // if(options.accept == 'other') {
    //     accept = {
    //         title: 'OtherFormat',
    //         mimeTypes: '.doc,.docx,.pdf,.ppt,.pptx,.xls,.xlsx,.zip,.rar,.tar,.gz,.z'
    //     };
    //     sizeLimit = 10*1024*1024;
    // }
    // // 只支持xls
    // if(options.accept == 'xls') {
    //     accept = {
    //         title: 'xls',
    //         mimeTypes: '.xls'
    //     };
    //     sizeLimit = 10*1024*1024;
    // }
    // // 音频
    // if(options.accept == 'office') {
    //     accept = {
    //         title: 'office',
    //         mimeTypes: '.doc,.ppt,.pptx,.xls,.xlsx'
    //     };
    //     sizeLimit = 10*1024*1024;
    // }

    // 初始化上传控件
    var uploader = WebUploader.create({
        auto: true,
        pick: {
            "id": "#"+ me.attr("id"),
            "multiple": options.multiple
        },
        server: options.server,
        formData:{
            authorization: options.authorization,
            policy: options.policy
        },
        accept: accept,
        // 支持重复上传
        duplicate :true,
        fileSingleSizeLimit: sizeLimit  // 限制大小
    });

    // 开始上传
    uploader.on("uploadStart", function() {
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            // $('body').append('<div class="shadow" style="display:flex;justify-content:center;align-items:center;padding-bottom:10%;width: 100%;height: 100%;position:fixed; top:0;left:0;background-color: #000;z-index: 9999;">\
            //     <div class="progress progress-striped pos-rel active" style="width: 50%;height: 28px;text-align:center;border-radius: 20px;z-index:9999;">\
            //         <div class="progress-bar progress-bar-success" style="line-height: 28px;width: 0%;">\
            //         <span style="color:#fff;">0%</span>\
            //         </div>\
            //     </div>\
            // </div>');
            $.showLoading("");
        }
    })
    // 上传中
    uploader.on('uploadProgress', function( file, percentage ) {
        // 上传视频时显示进度条
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            var percentage = Math.floor(percentage * 10000) / 100;
            // $(".progress span").text(percentage + "%");
            // $(".progress .progress-bar").width(percentage + "%")
            // $.showLoading(percentage + "%");
            var val = percentage + "%";
            $(".weui-toast_content").html(val);
        } else {
            layer.load(2, {
                opacity: 0.3
            });
        }
    })
    // 上传完成
    uploader.on('uploadSuccess', function(file, response) {
        if(options.accept == 'video' || options.accept == "all" || options.accept == "audio") {
            // $('.progress').remove();
            // $('.shadow').remove();
            $.hideLoading();
        } else {
            layer.closeAll('loading');
        }
        layer.closeAll('loading');
        // 新增一个文件名字段
        response.name = encodeURIComponent(file.name);
        options.callback(response);
    });
    // 上传错误
    uploader.on("error", function (type) {
        toastr.options = {  
            positionClass: "toast-center-center",              // 设置提示款显示的位置
            showDuration: "300",                               // 显示动画的时间
            hideDuration: "1000",                              //  消失的动画时间
            timeOut: "2000"                                    //  自动关闭超时时间 
        };
        if (type == "F_EXCEED_SIZE") {
            if(sizeLimit == 10*1024*1024) {
                toastr.error('文件大小不能超过10M');
            } else if(sizeLimit == 50*1024*1024) {
                toastr.error('文件大小不能超过50M');
            } else if(sizeLimit == 500*1024*1024) {
                toastr.error('文件大小不能超过500M');
            } else {
                toastr.error('文件大小不能超过10M');
            }
        } else {
            toastr.error("上传出错！请检查后重新上传！错误代码" + type);
        }
    });
}

// 选老师控件
$.fn.selectTeacher = function(options) {
    var options = $.extend({
        "multiSelect": false,
        "emptyMsg": "请选择老师",
        "openFolder": false,
        "isLoadData": false,
        "resultDom": null,          // 接收的dom对象
        "maxUser": 12,              // 文本显示人数
        "selectResult": new Array(),
        "callback": null
    }, options);

    var me = $(this);
    // 设置元素无法输入内容
    me.focus(function(){
        me.blur();
    }).css("cursor", "pointer");

    // 把模态框写入页面
    var modal = $('<div id="modal-select-teacher" class="modal fade" style="z-index:99999">\
        <div class="modal-dialog">\
            <div class="modal-content">\
                <div class="modal-header no-padding">\
                    <div class="table-header">\
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">\
                            <span class="white">&times;</span>\
                        </button> <span id="school-name"></span>\
                        教师选择\
                    </div>\
                </div>\
                <div class="modal-body no-padding"></div>\
                <div class="modal-footer no-margin-top" >\
                    <a href="javascript:;" class="btn btn-sm btn-primary" id="modal-select-teacher-confirm">\
                        <i class="ace-icon fa fa-check"></i> 确定\
                    </a>\
                </div>\
            </div>\
        </div>\
    </div>');

    // 点击事件
    me.click(function(){

        $("body").append(modal);
        $("body").parent().css("overflow-y","auto");
        // 重复加载，只显示弹窗
        /*
        if(options.isLoadData) {
            modal.modal();
            return;
        }
        */

        // 获取数据源
        ajax_get(teacherModalDataUrl, {hideLoading: true}, function(res) {

            // 初始化教师树状图
            var teacherTree = function(options, callback){
                var $data = null
                if(!("text" in options) && !("type" in options)){
                    $data = res.data;//the root tree
                    callback({ data: $data });
                    return;
                } else if("type" in options && options.type == "folder") {
                    if("additionalParameters" in options && "children" in options.additionalParameters)
                        $data = options.additionalParameters.children || {};
                    else $data = {}//no data
                }
                callback({ data: $data })
            }
            var treeWrap = $('<div id="modal-select-teacher-tree"></div>');
            modal.find(".modal-body").html(treeWrap);
            // 初始化
            treeWrap.ace_tree({
                dataSource: teacherTree,
                'multiSelect': options.multiSelect,
                'itemSelect' : true,
                'folderSelect': false,
            })
            // 是否展开节点
            if(options.openFolder) treeWrap.tree("discloseVisible");
            // 菜单选择，取消选择事件
            treeWrap.on('selected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) {
                    if(data.selected[i]){
                        options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
                    }
                }
            })
            treeWrap.on('deselected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) {
                    if(data.selected[i]){
                        options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
                    }
                }
            })

            // 展开选中值，然后又关闭
            if(options.resultDom && options.resultDom.val()) {
                var valueArray = options.resultDom.val().split(",");
                // 展开全部节点
                treeWrap.tree('discloseAll');
                // 赋值
                for(var i in valueArray) {
                    treeWrap.tree('selectItem', $('#' + valueArray[i]));
                }
                // 关闭节点
                treeWrap.tree('closeAll');
            }
            // 显示弹窗
            modal.modal();
            // 设置加载完成
            // options.isLoadData = true;
        })

        // 选择回调
        // modal.find("#modal-select-teacher-confirm").click(function(){
        modal.find("#modal-select-teacher-confirm").unbind("click").bind("click", function(){
            var isSelected = false;

            // 接收选择结果
            var idArray = new Array();
            var nameArray = new Array();
            var nameLength = 0;
            for(var i in options.selectResult) {
                isSelected = true;
                // 记录ID
                idArray.push(i);
                // 记录人数
                nameLength ++;
                if(nameLength < options.maxUser) nameArray.push(options.selectResult[i].name);
            }

            // 是否有选择用户
            if(!isSelected) {
                tips_alert(options.emptyMsg, false);
                return;
            }
            // modal.modal('hide');
            modal.next(".modal-backdrop").remove();
            modal.remove();

            // 是否有回调方法
            if(options.callback) {
                options.callback(options.selectResult);
            } else {
                // 保存结果
                var teacherName = nameArray.join("，");
                if(nameLength > options.maxUser) teacherName += '等' + nameLength.toString() + '人';
                me.val(teacherName);
                options.resultDom.val(idArray.join(","));
                $("body").parent().css("overflow-y","auto");
            }
        })
    })
}

// 显示附件文件
function append_attachment_file(appendDom, fileData){
    var fileName = decodeURIComponent(fileData.name);
    var fileLink = upyunUrl + fileData.url;
    var fileType = fileData.mimetype;

    // 预览链接
    var filePrev = fileLink;
    switch(fileType){
        // office文件类型
        case "application/msword":
        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
        case "application/vnd.ms-excel":
        case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
        case "application/vnd.ms-powerpoint":
        case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
            filePrev = officeViewer + filePrev;
            break;
        // pdf 文件类型
        case "application/pdf":
            filePrev = pdfViewer + filePrev;
            break;
    } 

    appendDom.append('<div class="alert alert-block alert-success attachment-file" data-name="'+ fileData.name +'" data-type="'+ fileType +'" data-link="'+ fileLink +'">\
        <button type="button" class="close">\
            <i class="ace-icon fa fa-times"></i>\
        </button>\
        <a title="预览" class="close mr10" target="_blank" href="'+ filePrev +'"><i class="ace-icon fa fa-paper-plane"></i> </a>\
        <p><i class="ace-icon fa fa-check"></i>\ '+ fileName +'</p>\
    </div>')
}

// 选角色控件
function select_role(roleData){
    var roleTree = $("#role-tree");
    // 初始化角色树状图
    var roleDatasource = function(options, callback){
        var $data = null
        if(!("text" in options) && !("type" in options)){
            $data = roleData;//the root tree
            callback({ data: $data });
            return;
        } else if("type" in options && options.type == "folder") {
            if("additionalParameters" in options && "children" in options.additionalParameters)
                $data = options.additionalParameters.children || {};
            else $data = {}//no data
        }
        callback({ data: $data })
    }
    roleTree.ace_tree({
        dataSource: roleDatasource,
        'multiSelect': true,
        'folder-open-icon': 'fa fa-plus-square-o',
        'folder-close-icon': 'fa fa-plus-square-o'
    }).tree("discloseAll");

    // 权限菜单选择，取消选择事件
    roleTree.on('selected.fu.tree', function (event, data) {
        var target = data.target;
        var targetId = target.attr.id;
        var targetType = target.type;
        // 目录添加选中图标
        if(targetType == 'folder') roleTree.find("span#" + targetId + "-label").before('<i class="icon-item ace-icon fa fa-check"></i>');
        // 写入选择结果
        set_selected_role_value(data);
    })
    roleTree.on('deselected.fu.tree', function (event, data) {
        var target = data.target;
        var targetId = target.attr.id;
        var targetType = target.type;
        // 目录删除选中图标
        if(targetType == 'folder') roleTree.find("span#" + targetId + "-label").prev('.fa-check').remove();
        // 写入选择结果
        set_selected_role_value(data);
    })
    
    // 获取选中的权限菜单
    function set_selected_role_value(result){
        var selected = result.selected;
        var result = new Array();
        for(var i in selected) {
            var item = selected[i];
            result.push(item.attr.id);
        }
        $("[name=role_id_set]").val(result.join(","));
    }
}

// 选择班级或资源年级控件
$.fn.selectSourceGrade = function(options) {
    var options = $.extend({
        "title": "选择年级",
        "multiSelect": false,
        "emptyMsg": "选择不能为空",
        "openFolder": false,
        "isLoadData": false,
        "resultDom": null,          // 接收的dom对象
        "maxUser": 12,              // 文本显示人数
        "selectResult": new Array(),
        "modalDataUrl": '',         // 获取资源类型url
        "callback": null
    }, options);
    var me = $(this);
    // 设置元素无法输入内容
    me.focus(function(){
        me.blur();
    }).css("cursor", "pointer");
    // 把模态框写入页面
    var modal = $('<div id="modal-select-source-grade" class="modal fade" style="z-index:99999;top: 16%;left: 0%;">\
        <div class="modal-dialog">\
            <div class="modal-content">\
                <div class="modal-header no-padding">\
                    <div class="table-header">\
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">\
                            <span class="white">&times;</span>\
                        </button> <span id="school-name"></span>' + options.title + '</div>\
                </div>\
                <div class="modal-body no-padding"></div>\
                <div class="modal-footer no-margin-top" >\
                    <a href="javascript:;" class="btn btn-sm btn-primary" id="modal-select-grade-confirm">\
                        <i class="ace-icon fa fa-check"></i> 确定\
                    </a>\
                </div>\
            </div>\
        </div>\
    </div>');
    // 点击事件
    me.click(function(){
        $("body").append(modal);
        $("body").parent().css("overflow-y","auto");
        // 获取数据源
        ajax_get(options.modalDataUrl, {hideLoading: true}, function(res) {
            // 初始化年级树状图
            var gradeTree = function(options, callback){
                var $data = null
                if(!("text" in options) && !("type" in options)){
                    $data = res.data;//the root tree
                    callback({ data: $data });
                    return;
                } else if("type" in options && options.type == "folder") {
                    if("additionalParameters" in options && "children" in options.additionalParameters)
                        $data = options.additionalParameters.children || {};
                    else $data = {}//no data
                }
                callback({ data: $data })
            }
            var treeWrap = $('<div id="modal-select-grade-tree"></div>');
            modal.find(".modal-body").html(treeWrap);
            // 初始化
            treeWrap.ace_tree({
                dataSource: gradeTree,
                'multiSelect': options.multiSelect,
                'itemSelect' : true,
                'folderSelect': false,
            })
            // 是否展开节点
            if(options.openFolder) treeWrap.tree("discloseVisible");
            // 菜单选择，取消选择事件
            treeWrap.on('selected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
            })
            treeWrap.on('deselected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
            })

            // 展开选中值，然后又关闭
            if(options.resultDom && options.resultDom.val()) {
                var valueArray = options.resultDom.val().split(",");
                // 展开全部节点
                treeWrap.tree('discloseAll');
                // 赋值
                for(var i in valueArray) {
                    treeWrap.tree('selectItem', $('#' + valueArray[i]));
                }
                // 关闭节点
                treeWrap.tree('closeAll');
            }
            // 显示弹窗
            modal.modal();
            $("body").css('padding', '0');
        })

        // 选择回调
        modal.find("#modal-select-grade-confirm").unbind("click").bind("click", function(){
            var isSelected = false;

            // 接收选择结果
            var idArray = new Array();
            var nameArray = new Array();
            for(var i in options.selectResult) {
                isSelected = true;
                // 记录ID
                idArray.push(i);
                nameArray.push(options.selectResult[i].name);
            }

            // 是否有选择用户
            if(!isSelected) {
                tips_alert(options.emptyMsg, false);
                return;
            }
            modal.next(".modal-backdrop").remove();
            modal.remove();

            // 是否有回调方法
            if(options.callback) {
                options.callback(options.selectResult);
            } else {
                // 保存结果
                var gradeName = nameArray[0];
                me.val(gradeName);
                options.resultDom.val(idArray[0]);
                $("body").parent().css("overflow-y","auto");
            }
        })
    })
}

// 选某年级的学生控件
$.fn.selectStudent = function(options) {
    var options = $.extend({
        "multiSelect": true,
        "emptyMsg": "请选择学生",
        "openFolder": false,
        "isLoadData": false,
        "resultDom": null,          // 接收的dom对象
        "maxUser": 4,              // 文本显示人数
        "selectResult": new Array(),
        "modalDataUrl": '',         // 获取资源类型url
        "callback": null
    }, options);

    var me = $(this);
    // 设置元素无法输入内容
    me.focus(function(){
        me.blur();
    }).css("cursor", "pointer");

    // 把模态框写入页面
    var modal = $('<div id="modal-select-student" class="modal fade" style="z-index:99999">\
        <div class="modal-dialog">\
            <div class="modal-content">\
                <div class="modal-header no-padding">\
                    <div class="table-header">\
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">\
                            <span class="white">&times;</span>\
                        </button> <span id="school-name"></span>\
                        学生选择\
                    </div>\
                </div>\
                <div class="modal-body no-padding"></div>\
                <div class="modal-footer no-margin-top" >\
                    <a href="javascript:;" class="btn btn-sm btn-primary" id="modal-select-student-confirm">\
                        <i class="ace-icon fa fa-check"></i> 确定\
                    </a>\
                </div>\
            </div>\
        </div>\
    </div>');

    // 点击事件
    me.click(function(){
        $("body").append(modal);
        $("body").parent().css("overflow-y","auto");
        // 获取数据源
        ajax_get(options.modalDataUrl, {hideLoading: true}, function(res) {
            // 初始化学生树状图
            var  studentTree = function(options, callback){
                var $data = null
                if(!("text" in options) && !("type" in options)){
                    $data = res.data;//the root tree
                    callback({ data: $data });
                    return;
                } else if("type" in options && options.type == "folder") {
                    if("additionalParameters" in options && "children" in options.additionalParameters)
                        $data = options.additionalParameters.children || {};
                    else $data = {}//no data
                }
                callback({ data: $data })
            }

            var treeWrap = $('<div id="modal-select-student-tree"></div>');
            modal.find(".modal-body").html(treeWrap);
            // 初始化
            treeWrap.ace_tree({
                dataSource: studentTree,
                'multiSelect': options.multiSelect,
                'itemSelect' : true,
                'folderSelect': false,
            })
            // 是否展开节点
            if(options.openFolder) treeWrap.tree("discloseVisible");
            // 菜单选择，取消选择事件
            treeWrap.on('selected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) {
                    if(data.selected[i]){
                        options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
                    }
                }
            })
            treeWrap.on('deselected.fu.tree', function (event, data) {
                options.selectResult = {};
                for(var i in data.selected) {
                    if(data.selected[i]){
                        options.selectResult[data.selected[i].attr.id] = {"name": data.selected[i].text};
                    }
                }
            })

            // 展开选中值，然后又关闭
            if(options.resultDom && options.resultDom.val()) {
                var valueArray = options.resultDom.val().split(",");
                // 展开全部节点
                treeWrap.tree('discloseAll');
                // 赋值
                for(var i in valueArray) {
                    treeWrap.tree('selectItem', $('#' + valueArray[i]));
                }
                // 关闭节点
                treeWrap.tree('closeAll');
            }
            // 显示弹窗
            modal.modal();
        })

        // 选择回调
        modal.find("#modal-select-student-confirm").unbind("click").bind("click", function(){
            var isSelected = false;

            // 接收选择结果
            var idArray = new Array();
            var nameArray = new Array();
            var nameLength = 0;
            for(var i in options.selectResult) {
                isSelected = true;
                // 记录ID
                idArray.push(i);
                // 记录人数
                nameLength ++;
                if(nameLength <= options.maxUser) nameArray.push(options.selectResult[i].name);
            }

            // 是否有选择用户
            if(!isSelected) {
                tips_alert(options.emptyMsg, false);
                return;
            }
            modal.next(".modal-backdrop").remove();
            modal.remove();

            // 是否有回调方法
            if(options.callback) {
                options.callback(options.selectResult);
            } else {
                // 保存结果
                var studentName = nameArray.join("，");
                if(nameLength > options.maxUser) studentName += '...等' + nameLength.toString() + '人';
                me.val(studentName);
                // 适用于不是点击本输入框的情况，如添加考试数据页面
                $("[name=student-name]").val(studentName);
                options.resultDom.val(idArray.join(","));

                $("body").parent().css("overflow-y","auto");
            }
        })
    })
}

//获取时间
function getNowTime(excludeSec){
    var date=new Date();
    var year=date.getFullYear();
    var month=date.getMonth() + 1;
    var day=date.getDate();
    var hour=date.getHours();
    var minute=date.getMinutes();
    var second=date.getSeconds();
    //这样写显示时间在1~9会挤占空间；所以要在1~9的数字前补零;
    if(month < 10) {
        month = '0' +  month;
    }
    if(day < 10) {
        day = '0' + day;
    }
    if(hour < 10) {
        hour = '0' + hour;
    }
    if(minute < 10) {
        minute = '0' + minute;
    }
    if(second < 10) {
        second = '0' + second;
    }
    var time = '';
    if(excludeSec) {
        time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
    } else {
        time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return time;
}

// 判断是否ios
function isIos() {
    var u = navigator.userAgent, app = navigator.appVersion;
    // var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
    var isiOS = u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    return isiOS;
}

